$("#type").bind("change",function(event){
	var value = $(this).val();
	if(value=="1"){
		$("#orderTr").show();
	} else {
		$("#orderTr").hide();
		$("#orderId").val(-1);
	}
});


function setPredictPayDate(objEnddate, days){
    var dt = new Date(parseInt($dp.cal.getP('y')), parseInt($dp.cal.getP('M'))-1, parseInt($dp.cal.getP('d'))+days);
    objEnddate.value = dt.format("yyyy-MM-dd");
}       

$(document).ready(function(){
	try{
		$.jgrid.no_legacy_api = true;
		$.jgrid.useJSON = true;
		$.jgrid.formatter.integer.thousandsSeparator = ',';
		$.jgrid.formatter.number.thousandsSeparator = ',';
		$.jgrid.formatter.currency.thousandsSeparator = ',';
		
		$("#orderItemsTable").jqGrid({						
			url : appRoot + '/purchaseItem/list/' + purchaseId + '?ajax=1',
			editurl : appRoot + '/purchaseItem/save?ajax=1&purchaseId=' +purchaseId,
			datatype : 'json',
			mtype : 'GET',
			jsonreader: {             
				repeatitems: false,
				id:'Id',
				root:'rows'
			}, 
			
			colNames : [ 'id','objectId','工程单号', '英文品名', '中文品名', '数量','单位', '单价','总价'],
			colModel : [
	       {
				name : 'id',
				index : 'id',
				editable : true,
				hidden:true
				
			}, {
				name : 'objectId',
				index : 'objectId',
				editable : true,
				hidden:true
			},
			{
				name : 'customerPurchaseNo',
				index : 'customerPurchaseNo',
				width : 120,
				align : 'left',
				resizable : false,
				editable : true,
				edittype:'text',
				sortable: false,
				editrules : {
					required : true
				}

			}, {
				name : 'englishName',
				index : 'englishName',
				width : 200,
				editable : true,
				edittype:'text',
				sortable: false,
				editrules : {
					required : true
				}
			}, {
				name : 'name',
				index : 'name',
				width : 120,
				editable : true,
				edittype:'text',
				sortable: false,
				editrules : {
					required : true
				}
			}, {
				name : 'quantity',
				index : 'quantity',
				width : 60,
				align : 'right',
				editable : true,
				edittype:'text',
				sortable: false,
				editrules : {
					required : true,
					number : true
				}							
			}, {
				name : 'unit',
				index : 'unit',
				width : 40,
				editable : true,
				edittype:'select',
				formatter:'select',
				editoptions : {
			        value :units
			    },
				editrules : {
					required : true
				}
			}, {
				name : 'unitPrice',
				index : 'unitPrice',
				width : 60,
				align : 'right',
				editable : true,
				sortable: false,
				editrules : {
					required : true,
					number : true
				}
			}, {
				name : 'amount',
				index : 'amount',
				width : 100,
				align : 'right',
				sortable: false,
				editable : false
			}
			],
			gridComplete: function(){
				var grid = $("#orderItemsTable");
				sum = grid.jqGrid('getCol', 'amount', false, 'sum'); 
				grid.jqGrid('footerData','set', {customerPurchaseNo:"合计:",ID: 'Total:', amount: sum}); 
			},
			width: 730,
			height : 400,
			gridview:true,
			pager : $('#pager'),
			nowNum : 100,
			rowNum : 100,
			sortable:false,
			scrollrows: true,
			viewrecords : true,
			footerrow: true,
			shrinkToFit:false,
			caption : '大货生产前要求'
		}).navGrid("#pager",{edit:purchaseEditable,add:purchaseEditable,del:purchaseEditable,search:false});
		
	}catch(e){}
	
	$("#orderId").change(function(){
        var orderId = $(this).val();
        if(orderId){
            if(confirm("需要导入该订单的明细数据吗？")){
            	$("#notice").html("数据导入中...").show();
            	 $.ajax({
                     url:appRoot + "/orderItem/importToPurchase/" + orderId + "/" + purchaseId,
                     type:'post',
                     dataType:'json',
                     success:function(msg){
                         if(msg.result){
                        	 $("#orderItemsTable").trigger("reloadGrid");
                        	 $("#notice").html("成功导入" + msg.result + "条订单明细");
                         }else{
                        	 $("#notice").html("没有明细需要导入");
                         }
                     }
                });
            }
        }
    });
	
	$(".colorbox").colorbox({iframe:true, innerWidth:750, innerHeight:460});

	$(".picture").colorbox();
});

fileLimit = 3;

function createUploader(){
    var filelimituploader = new qq.FileUploader({
        element: $('#filelimit-fine-uploader')[0],
        action: appRoot + '/picture/upload/3/' + purchaseId+ '?ajax=1',
        debug: false,
        demoMode: false,
        forceMultipart:true,
        allowedExtensions: ['jpeg', 'jpg', 'gif', 'png'],
        sizeLimit: fileUploadSize,
        uploadButtonText:"上传图片",
        cancelButtonText:"取消",
        failUploadText:"上传失败",
        onSubmit: function(id, fileName) {
        	purchaseFileCount ++;
            if(purchaseFileCount > fileLimit) {
                alert("已经达到最大上传文件数量，不能再上传了！");
                purchaseFileCount--;
                return false;
            }
        },
        onCancel: function(id, fileName) {
        	purchaseFileCount--;
            if(purchaseFileCount <= fileLimit) {
                $('#filelimit-fine-uploader .qq-upload-button').show();
            }
        },
        onComplete: function(id, fileName, responseJSON) {
            if (responseJSON.success) {
                var fileId = responseJSON.fileId;
                var fileSuffix = responseJSON.fileSuffix;
                var fileName = responseJSON.fileName;
                $('#filelimit-fine-uploader').append('<div style="float: left;width: 200px;" id="d_f_' + fileId + '"><a href="' + appRoot + '/download/' 
                         + fileId + fileSuffix + '" title="' + fileName + '" class="picture"><img alt="' + fileName + '" src="' + appRoot + '/download/'
                         + fileId + fileSuffix + '" width="150">'
                         + '<a href="javascript:deletePicture(\'' + fileId + '\')">删除</a></div>');
                $(".picture").colorbox();
            }
        }
    });
    $(".qq-upload-list").hide();
}

function deletePicture(fileId){
    if(fileId){
        if(confirm("你确定要删除此图片吗？")){
            $.ajax({
                 url:appRoot + "/picture/delete/" + fileId + "?ajax=1",
                 type:'post',
                 dataType:'json',
                 success:function(msg){
                     if(msg.success){
                         alert("删除成功");
                         purchaseFileCount--;
                         $("#d_f_" + fileId).remove();
                     }
                 }
            });
        }
    }
}

//page
function getCustomer(id){
	$("#suberror").hide();
    $("#subnotice").hide();
    $("#otherUsers").val("");
    $("input[type='checkbox']").each(function(){
        $(this).attr("checked",false);
    });
    if(id){
        $.ajax({
             url: appRoot + "/supplier/get/" + id,
             type:'post',
             dataType:'json',
             success:function(msg){
                 $("#customer_2").text(msg.entity.name).attr("title",msg.entity.email);
             }
        });
    }
}

function notify(){
    if(currentPurchaseId==null){
        return;
    }
    $(".audit").attr("disabled",true);
    $("#notifyButton").attr("disabled",true);
    var selected = getCheckedValuesString(document.getElementsByName("users"));
    var customer = ($("#customer_1").attr("checked")=="checked");
    var others = $("#otherUsers").val();
    if(!selected&&!customer&&!others){
        $("#suberror").html("请至少选择一个接收者").show();
        $(".audit").attr("disabled",false);
        $("#notifyButton").attr("disabled",false);
    }else{
        $("#suberror").hide();
        $("#subnotice").html("操作进行中...").show();
        $.ajax({
             url: appRoot + "/purchase/notify/" + currentPurchaseId + "?date=" + (new Date()).valueOf(),
             type:'post',
             dataType:'json',
             data:'purchasers=' + (selected==null?"":selected) + "&customer=" + customer + "&others=" + others,
             success:function(msg){
                 if(msg.result){
                     showMessage("邮件已发送");
                 }else{
                     showMessage("操作失败");
                 }
                 $(".audit").attr("disabled",false);
                 $("#notifyButton").attr("disabled",false);
                 jQuery.fn.colorbox.close();
             }
        });
    }
}

function audit(orderId,action){
	$("#notice").html("操作进行中...").show();
	$(".audit").attr("disabled",true);
	$.ajax({
         url: appRoot + "/purchase/audit/" + orderId,
         type:'post',
         dataType:'json',
         data:"status=20" ,
         success:function(msg){
        	 if(msg.result){
        		 window.location.href= appRoot +'/purchase/' + action + '?message=' + encodeURIComponent('操作成功');
        	 }else{
        		 $("#notice").html("").hide();
        		 showMessage("操作失败");
        		 $(".audit").attr("disabled",false);
        	 }
         }
	});
}

function pay(orderId,action){
	if(confirm("确认已付款？")){
		$(".audit").attr("disabled",true);
	    $.ajax({
	         url: appRoot + "/purchase/pay/" + orderId,
	         type:'post',
	         dataType:'json',
	         success:function(msg){
	             if(msg.result){
	                 window.location.href= appRoot + '/purchase/' + action + '?message=' + encodeURIComponent('操作成功');
	             }else{
	                 showMessage("操作失败");
	                 $(".audit").attr("disabled",false);
	             }
	         }
	    });
	}
}

function finish(orderId,action){
    $(".audit").attr("disabled",true);
    if(confirm("你确认该采购单已完成？")){
        $.ajax({
            url: appRoot + "/purchase/finish/" + orderId,
            type:'post',
            dataType:'json',
            success:function(msg){
                if(msg.result){
                    window.location.href= appRoot + '/purchase/' + action + '?message=' + encodeURIComponent('操作成功');
                }else{
                    showMessage("操作失败");
                    $(".audit").attr("disabled",false);
                }
            }
       });
    }else{
        $(".audit").attr("disabled",false);
    }
}

function backward(action){
	if(currentPurchaseId==null){
		return;
	}
	var reason = $("#reason").val();
    if(!reason){
    	$("#suberror1").html("请填写退回原因").show();
    	return;
    }
	$("#subnotice1").html("操作进行中...").show();
	$("#suberror1").html("").hide();
	$(".bacward").attr("disabled",true);
	$("#backwardButton").attr("disabled",true);
	$.ajax({
         url: appRoot + "/purchase/backward/" + currentPurchaseId + "?reason=" +  encodeURIComponent(reason) + "&date=" + (new Date()).valueOf(),
         type:'post',
         dataType:'json',
         success:function(msg){
        	 if(msg.result){
        		 window.location.href= appRoot +'/purchase/' + action + '?message=' + encodeURIComponent('操作成功');
        	 }else{
        		 var message = msg.message;
        		 if(message==null){
        			 message = "操作失败";
        		 }
        		 $("#subnotice1").html("").hide();
        		 $("#suberror1").html(message).show();
        		 $(".bacward").attr("disabled",false);
        		 $("#backwardButton").attr("disabled",false);
        	 }
         }
	});
}